import { listToTree } from "@/utils/generatorRouters";
import { RouterModel } from "@/models/routerModel";
import { messageCof } from "./../../utils/message";
import { reactive, ref, toRaw } from "vue";
import User from "@/api/user";
import { defineStore } from "pinia";
import history from "@/utils/history";
import router from "@/router";
export const userStore = defineStore("user", () => {
  let loading = ref<boolean>(false);
  let menu: Array<RouterModel> = reactive([]);
  let token = ref<string>(localStorage.getItem("app_token") || "");
  function setToken(token: string) {
    return localStorage.setItem("app_token", token);
  }

  function getToken() {
    return localStorage.getItem("app_token");
  }

  function removeToken() {
    localStorage.removeItem("app_token");
  }
  function loginSuccess() {
    const redirect = history().redirect;
    router.replace({ path: redirect });
  }

  async function userLogin(username: string, password: string) {
    loading.value = true;

    try {
      const res = await User.login({ username, password });
      if (res.data.status == 200) {
        messageCof("登录成功！", "success");
        setToken(res.data?.token);
        token.value = res.data?.token;
        try {
          loginSuccess();
        } finally {
          loading.value = false;
        }
      } else {
        loading.value = false;
      }
    } finally {
      loading.value = false;
    }
  }
  async function getMenu() {
    const menu_result = await User.getUserMenu();
    const arr: RouterModel[] = [];
    listToTree(menu_result.data.data, arr, 0);
    localStorage.setItem("menuData", JSON.stringify(arr));
    menu.push(...arr);
    localStorage.removeItem("menuData");
  }
  return { userLogin, getMenu, loading, token, menu };
});
